<template>
  <el-dialog v-model="visible" title="选择社区" width="80%" :before-close="handleClose">
    <!-- 搜索栏 -->
    <div class="handle-box">
      <el-input v-model="searchForm.moduleName" placeholder="社区名称" class="handle-input mr10" clearable />
      <el-select v-model="searchForm.forumCategory" placeholder="社区分类" class="handle-input mr10" clearable>
        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border class="table" ref="communityTable" header-cell-class-name="table-header"
      @selection-change="handleSelectionChange" @row-click="handleRowClick" row-key="id">
      <el-table-column type="radio" width="55">
        <template #default="scope">
          <el-radio v-model="selectedCommunity" :label="scope.row.id"
            @change="handleRadioChange(scope.row)">&nbsp;</el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="社区ID" width="100" />
      <el-table-column prop="communityName" label="社区名称" min-width="150" />
      <el-table-column prop="categoryName" label="分类名称" min-width="120" />
      <el-table-column prop="description" label="简介" min-width="200">
        <template #default="scope">
          <div class="description-cell">
            {{ scope.row.description || '-' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="image" label="图片" align="center">
        <template #default="scope">
          <el-image v-if="scope.row.image" :src="scope.row.image" style="width: 50px; height: 50px;" fit="cover"
            :preview-src-list="[scope.row.image]" preview-teleported />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ scope.row.createTime ? dateFormat(scope.row.createTime) : '-' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="selected-info">{{ selectedCommunityData ? `已选择：${selectedCommunityData.communityName}` : '未选择社区'
        }}</span>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import moment from "moment";
import { getCommunities, getForumCategories } from "@/api/content";

export default {
  name: "SelectCommunity",
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    // 已选中的社区数据
    selectedData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'confirm'],
  data() {
    return {
      searchForm: {
        moduleName: "",
        forumCategory: "",
      },
      tableData: [],
      // 社区分类列表
      categoryOptions: [],
      selectedCommunity: null, // 当前选中的社区ID
      selectedCommunityData: null, // 当前选中的社区完整数据
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  computed: {
    visible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit('update:modelValue', val);
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.getForumCategoriesList();
        this.getData();
        this.initSelectedData();
      }
    }
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      if (this.searchForm.moduleName) {
        params.moduleName = this.searchForm.moduleName;
      }
      if (this.searchForm.forumCategory) {
        params.forumCategory = this.searchForm.forumCategory;
      }

      return params;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const response = await getCommunities(params);

        if (response && response.data) {
          // 根据接口字段映射数据
          this.tableData = (response.data.rows || response.data).map(item => ({
            id: item.id,
            communityName: item.moduleName || '',
            categoryId: item.forumCategory || '',
            categoryName: item.forumCategoryName || '',
            // 添加一级分类信息
            parentCategoryId: item.forumCategory || '',
            parentCategoryName: item.forumCategoryName || '',
            description: item.moduleBlurb || '',
            image: item.moduleImgUrl || '',
            createTime: item.createTime,
            updateTime: item.updateTime,
            // 保留原始数据
            _original: item
          }));

          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        console.error('获取社区数据失败:', error);
        this.$message.error('获取社区数据失败');
      }
    },
    // 初始化已选中的数据
    initSelectedData() {
      if (this.selectedData) {
        this.selectedCommunity = this.selectedData.id;
        this.selectedCommunityData = { ...this.selectedData };
      } else {
        this.selectedCommunity = null;
        this.selectedCommunityData = null;
      }
    },
    // 处理单选变化
    handleRadioChange(row) {
      this.selectedCommunityData = { ...row };
    },
    // 处理行点击
    handleRowClick(row) {
      this.selectedCommunity = row.id;
      this.selectedCommunityData = { ...row };
    },
    // 处理表格选择变化（兼容性方法，实际使用单选）
    handleSelectionChange(selection) {
      // 单选模式下不需要处理
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false;
    },
    // 确认选择
    handleConfirm() {
      this.$emit('confirm', this.selectedCommunityData);
      this.handleClose();
    },
    // 获取社区分类列表
    async getForumCategoriesList() {
      try {
        const response = await getForumCategories({ limit: 1000, offset: 1 });
        if (response && response.data) {
          this.categoryOptions = (response.data.rows || response.data).map(item => ({
            value: item.id,
            label: item.categoryName || item.name,
            id: item.id,
            categoryName: item.categoryName || item.name
          }));
        }
      } catch (error) {
        console.error('获取社区分类列表失败:', error);
        this.$message.error('获取社区分类列表失败');
      }
    }
  },
};
</script>

<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.handle-input.el-select {
  width: 200px;
}

.table {
  width: 100%;
  font-size: 14px;
}

.mr10 {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.description-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}
</style>